package wonder.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.StringWriter;
import java.util.Map;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;

/**
 * <p>
 * MessageTextTemplateVelocity class.
 * </p>
 * <p>
 * The class builds a text from a template and a Map of values by using the <a
 * href="http://velocity.apache.org/">Apache Velocity framework</a>. The
 * MessageTextProvidedVelocity class expects the <b>template</b> parameter to be
 * the file path to the <b>template file</b>.
 * </p>
 *
 * @author u211354
 * @version $Id: $
 */
public class MessageTextTemplateVelocity implements IMessageTextProvider {
    private static final Logger logger = LoggerHelper.getLogger();

    /**
     * <p>Constructor for MessageTextTemplateVelocity.</p>
     *
     * @throws java.lang.Exception if any.
     */
    public MessageTextTemplateVelocity() throws Exception {
        Velocity.init();
    }

    /**
     * {@inheritDoc}
     * <p>
     * getMessage
     * </p>
     */
    @Override
    public String getMessage(String template, Map<String,Object> data)
            throws Exception {

        VelocityContext context = new VelocityContext();
        context.put("map", data);

        StringWriter w = new StringWriter();

        if (Velocity.resourceExists(template)) {
            Velocity.mergeTemplate(template, DEFAULT_ENCODING, context, w);
        } else {
            // the resource is not available via a ResourceLoader
            File tpl = new File(template);
            logger.debug("Loading resource from the file system: {}",
                    tpl.getAbsolutePath());

            if (tpl.exists()) {
                template = StreamHelper.streamToString(
                        new FileInputStream(tpl), DEFAULT_ENCODING);
                Velocity.evaluate(context, w, "MessageTextTemplateVelocity",
                        template);
            } else throw new Exception("Template not found: "
                    + tpl.getAbsolutePath());
        }

        return w.toString();
    }
}
